<?php
//======================================================
// Copyright (C) 2004 John W. Holmes, All Rights Reserved
//
// This file is part of the Unit Command Climate
// Assessment and Survey System (UCCASS)
//
// UCCASS is free software; you can redistribute it and/or
// modify it under the terms of the Affero General Public License as
// published by Affero, Inc.; either version 1 of the License, or
// (at your option) any later version.
//
// http://www.affero.org/oagpl.html
//
// UCCASS is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// Affero General Public License for more details.
//======================================================

class UCCASS_SurveyAdmin extends UCCASS_Main
{
    function UCCASS_SurveyAdmin()
    { $this->load_configuration(); }

    /*************
    * ADMIN PAGE *
    *************/
    
    function admin()
    {
        $data = array();
        $template = 'admin.tpl';

        $this->ChekNivel();
		
       
    
        
		$admin_priv = $this->_CheckLogin('admin.php');//$admin_priv=admin privilegio
        if(!$admin_priv)
        {
            $template = 'login.tpl';
            if(isset($_REQUEST['password']))
            {
                $data['message'] = 'Incorrect Username and/or Password';
                $data['username'] = $this->SfStr->getSafeString($_REQUEST['username'],SAFE_STRING_TEXT,1);
            }
            $data['page'] = 'admin.php';
        }
        else
		{
			
           
			
			if(isset($_REQUEST['userNew'])){
			 
			  $template = $this->nuevoUsuario('x0');
			  return $template;
			}
			
			//PARA INSERTAR NUEVOS USUARIOS
			if(isset($_REQUEST['insertar_admin_users']))
            { $this->insert_admin_users();}
	        
			//cuando presiona en editar en algun usuario de la lista
	        //hace esto y retorna el admin_b.tpl con los  datos del usuario
			if(isset($_REQUEST['editAdmin'])){
			  $aid_ = $_REQUEST['aid_'];
			  $template = $this->editarUsuarios($aid_);
			  
			  return $template;
			}
            
			//CUANDO EN LA EDICION DE USUARIOS PRESIONA EL BOTON DE ACTUALIZAR, HACE ESTO
			if(isset($_REQUEST['actualizar_admin_users']))
            { $this->actualizar_admin_users(); }

        	
            //LISTAR TODOS LOS ADMINISTRADORES
                       
            //select admin, admin de categorias, admin de estadisticas	
			$admin_type = array();

			$query = "SELECT at_id, name FROM {$this->CONF['db_tbl_prefix']}admin_type ORDER BY name ASC";
							
			$rs = $this->db->Execute($query);
            if($rs === FALSE)
            { $this->error("Error selecting admin: " . $this->db->ErrorMsg()); }
           
			while($r = $rs->FetchRow())
            {
                $data['admin_type']['uid'][] = $r['at_id'];
                $data['admin_type']['name'][] = $this->SfStr->getSafeString($r['name'],SAFE_STRING_TEXT);
            }
           
            //////////////////////////////////////////////////////////
			
			///////categorias, deportes, musica, politica
				$category = array();     
				$query1 = "SELECT cid, category FROM {$this->CONF['db_tbl_prefix']}category WHERE active = 1 ORDER BY category ASC";
				
				$rs1 = $this->db->Execute($query1);
				if($rs1 === FALSE)
				{ $this->error("Error selecting category: " . $this->db->ErrorMsg()); }
				
				while($r1 = $rs1->FetchRow())
				{
					$category['cid'][] = $r1['cid'];
					$category['category'][$r1['cid']] = $this->SfStr->getSafeString($r1['category'],SAFE_STRING_TEXT);
				}
				
		        //////////1,2,3 - admin, admin categorias, admin estadisticas - 96,98,99.
				$data['cid'] = $category['cid'];
				$this->smarty->assign('category',$category);
			////////////////////////////////////////////////
				
			//Selecciona usuarios with Admin and Create privileges: adminUniversia, DeportesUniversia, estadisticasUniversia
            $query = "SELECT a_id, name, username, password, email, place, type, active FROM
                      {$this->CONF['db_tbl_prefix']}admin ORDER BY username ASC";
           
           /*$query = "SELECT a_id, name, username, password, email, place, type, active FROM
                       {$this->CONF['db_tbl_prefix']}admin WHERE a_id != 0 ORDER BY username ASC";*/
            
			$rs = $this->db->Execute($query);
            if($rs === FALSE)
            { $this->error('Unable to get user permissions: ' . $this->db->ErrorMsg()); return; }
            $x = 0;
            while($r = $rs->FetchRow($rs))
            {
                $data['users'][$x]['uid'] = $r['a_id'];
                $data['users'][$x]['name'] = $this->SfStr->getSafeString($r['name'],SAFE_STRING_TEXT);
                $data['users'][$x]['email'] = $this->SfStr->getSafeString($r['email'],SAFE_STRING_TEXT);
                $data['users'][$x]['username'] = $this->SfStr->getSafeString($r['username'],SAFE_STRING_TEXT);
                $data['users'][$x]['password'] = $this->SfStr->getSafeString($r['password'],SAFE_STRING_TEXT);
				$data['users'][$x]['place'] = $this->SfStr->getSafeString($r['place'],SAFE_STRING_TEXT);		
				$data['users'][$x]['type'] = $this->SfStr->getSafeString($r['type'],SAFE_STRING_TEXT);
	
				$data['users'][$x]['active'] = $this->SfStr->getSafeString($r['active'],SAFE_STRING_TEXT);
				$data['users'][$x]['active_selected'] = "";
				
				if($data['users'][$x]['active']=="1")
				{
					$data['users'][$x]['active_selected'] = "checked";
				}
							
				$admin_category = array();// le corresponde una o mas categorias para cada usuario de categorias
				$query2 = "SELECT ad.a_id, ad.cid, category FROM {$this->CONF['db_tbl_prefix']}admin_type_category ad inner join {$this->CONF['db_tbl_prefix']}category c  on c.cid=ad.cid WHERE a_id = ".$data['users'][$x]['uid']."";
											
				$rs2 = $this->db->Execute($query2);	
				
				if($rs2 === FALSE)
				{$this->error("Error selecting admin category: " . $this->db->ErrorMsg()); }
				
				while($r2 = $rs2->FetchRow())
				{
					$admin_category['a_id'][] = $r2['a_id'];
					$admin_category['cid'][] = $r2['cid'];
					$admin_category['category'][$r2['cid']] = $r2['category'];
				}
                 		
								
				$sobrante = array_diff($category['category'],$admin_category['category']);
				
				
				$sob = array();
				foreach ($sobrante as $key => $value)
				{
				
					$sob['key'][] = $key;
					$sob['value'][] = $value;
				} 
				
				$data['users'][$x]['category_selected'] = $admin_category;
				$data['users'][$x]['category_no_selected'] = $sob;
              
			    $tipos_category = array(); //los tipos de categoria que le pertenece a cada administrador de categorias deportes y musica para depmus,etc   
				$query3 = "SELECT a_id, cid FROM {$this->CONF['db_tbl_prefix']}admin_type_category WHERE a_id = ".$data['users'][$x]['uid']."";
				
				$rs3 = $this->db->Execute($query3);				
				if($rs3 === FALSE)
				{ $this->error("Error selecting admin category: " . $this->db->ErrorMsg()); }
				while($r3 = $rs3->FetchRow())
				{
					$tipos_category['a_id'][] = $r3['a_id'];
					$tipos_category['cid'][] = $r3['cid'];
				}

				$tipos = array();
				$tipos = implode("/", $tipos_category['cid']);
				
				$data['users'][$x]['tipos'] = $tipos;
				
				if(isset($erruid[$r['uid']]))
                {$data['users'][$x]['erruid'] = 1; }
				 $x++;
            }

           /*for($y=0;$y<1;$y++)
            { $data['users'][$x++]['uid'] ='x'.$y; }*/
        }

		$this->smarty->assign_by_ref('data',$data);
	
        $retval = $this->smarty->Fetch($this->template.'/'.$template);

        return $retval;
    }
	
	
	function editarUsuarios($id){
	   $query = "SELECT a_id, name, username, password, email, place, type, active FROM
                      {$this->CONF['db_tbl_prefix']}admin WHERE a_id = $id";
           
		$rs = $this->db->Execute($query);
		if($rs === FALSE)
		{ $this->error('Unable to get user permissions: ' . $this->db->ErrorMsg()); return; }
		$x = 0;
		while($r = $rs->FetchRow($rs))
		{
			$data['users'][$x]['uid'] = $r['a_id'];
			$data['users'][$x]['name'] =$this->SfStr->getSafeString($r['name'],SAFE_STRING_TEXT);
			$data['users'][$x]['email'] = $this->SfStr->getSafeString($r['email'],SAFE_STRING_TEXT);
			$data['users'][$x]['username'] = $this->SfStr->getSafeString($r['username'],SAFE_STRING_TEXT);
			$data['users'][$x]['password'] = $this->SfStr->getSafeString($r['password'],SAFE_STRING_TEXT);
			$data['users'][$x]['place'] = $this->SfStr->getSafeString($r['place'],SAFE_STRING_TEXT);		
			$data['users'][$x]['type'] = $this->SfStr->getSafeString($r['type'],SAFE_STRING_TEXT);
			$data['users'][$x]['active'] = $this->SfStr->getSafeString($r['active'],SAFE_STRING_TEXT);
			  $data['users'][$x]['active_selected'] = "";
			  if($data['users'][$x]['active']=="1")
			  {
			    $data['users'][$x]['active_selected'] = "checked";
			  }
		    
		}
		//if($data['users'][$x]['type'] == 2){
	      $admin_type = array();
          $query = "SELECT at_id, name FROM {$this->CONF['db_tbl_prefix']}admin_type ORDER BY name ASC";
		  $rs = $this->db->Execute($query);
          if($rs === FALSE)
          { $this->error("Error selecting admin: " . $this->db->ErrorMsg()); }
           
		  while($r = $rs->FetchRow())
          {
              $data['admin_type']['uid'][] = $r['at_id'];
              $data['admin_type']['name'][] = $this->SfStr->getSafeString($r['name'],SAFE_STRING_TEXT);
          }
		  
		  
		  $category = array();     
		  $query1 = "SELECT cid, category FROM {$this->CONF['db_tbl_prefix']}category WHERE active = 1 ORDER BY category ASC";
		  $rs1 = $this->db->Execute($query1);
		  if($rs1 === FALSE)
		  { $this->error("Error selecting category: " . $this->db->ErrorMsg()); }
		  while($r1 = $rs1->FetchRow())
		  {
			$category['cid'][] = $r1['cid'];
			$category['category'][$r1['cid']] = $this->SfStr->getSafeString($r1['category'],SAFE_STRING_TEXT);
		  }
		  $data['cid'] = $category['cid'];
		  $this->smarty->assign('category',$category);
		  
		  
		  $admin_category = array();// le corresponde una o mas categorias para cada usuario de categorias
		  $query2 = "SELECT ad.a_id, ad.cid, category FROM {$this->CONF['db_tbl_prefix']}admin_type_category ad inner join {$this->CONF['db_tbl_prefix']}category c  on c.cid=ad.cid WHERE a_id = ".$id."";
		  $rs2 = $this->db->Execute($query2);	
				
		  if($rs2 === FALSE)
		  {$this->error("Error selecting admin category: " . $this->db->ErrorMsg()); }
				
		  while($r2 = $rs2->FetchRow())
		  {
			$admin_category['a_id'][] = $r2['a_id'];
			$admin_category['cid'][] = $r2['cid'];
			$admin_category['category'][$r2['cid']] = $r2['category'];
		  }
                 		
		  $sobrante = array_diff($category['category'],$admin_category['category']);
		  $sob = array();
		  foreach ($sobrante as $key => $value)
		  {
			$sob['key'][] = $key;
			$sob['value'][] = $value;
		  } 
				
		  $data['users'][$x]['category_selected'] = $admin_category;
		  $data['users'][$x]['category_no_selected'] = $sob;
		  
		  
		  $tipos_category = array(); //los tipos de categoria que le pertenece a cada administrador de categorias deportes y musica para depmus,etc   
		  $query3 = "SELECT a_id, cid FROM {$this->CONF['db_tbl_prefix']}admin_type_category WHERE a_id = ".$id."";
		  $rs3 = $this->db->Execute($query3);				
		  if($rs3 === FALSE)
		  {$this->error("Error selecting admin category: " . $this->db->ErrorMsg()); }
			
		  while($r3 = $rs3->FetchRow())
		  {
			$tipos_category['a_id'][] = $r3['a_id'];
			$tipos_category['cid'][] = $r3['cid'];
		  }
            
		  $tipos = array();
		  $tipos = implode("/", $tipos_category['cid']);
				
		  $data['users'][$x]['tipos'] = $tipos;
				
		  if(isset($erruid[$r['uid']]))
          {$data['users'][$x]['erruid'] = 1; }
		//}
		$template = 'admin_b.tpl';
		$this->smarty->assign_by_ref('data',$data);
	    $retval = $this->smarty->Fetch($this->template.'/'.$template);
        return $retval;
	}
	
	
	function nuevoUsuario($id)
	{
	   	$x = 0;
		$data['users'][$x]['uid'] = $id;
		$data['users'][$x]['name'] = '';
		$data['users'][$x]['email'] = '';
		$data['users'][$x]['username'] = '';
		$data['users'][$x]['password'] = '';
		$data['users'][$x]['place'] = '';		
		$data['users'][$x]['type'] = 1;
		$data['users'][$x]['active'] = '';
		$data['users'][$x]['active_selected'] = '';
		
		    
		
		  $admin_type = array();
          $query = "SELECT at_id, name FROM {$this->CONF['db_tbl_prefix']}admin_type ORDER BY name ASC";
		  $rs = $this->db->Execute($query);
          if($rs === FALSE)
          { $this->error("Error selecting admin: " . $this->db->ErrorMsg()); }
           
		  while($r = $rs->FetchRow())
          {
              $data['admin_type']['uid'][] = $r['at_id'];
              $data['admin_type']['name'][] = $this->SfStr->getSafeString($r['name'],SAFE_STRING_TEXT);
          }
		  
		  
		  $category = array();     
		  $query1 = "SELECT cid, category FROM {$this->CONF['db_tbl_prefix']}category WHERE active = 1 ORDER BY category ASC";
		  $rs1 = $this->db->Execute($query1);
		  if($rs1 === FALSE)
		  { $this->error("Error selecting category: " . $this->db->ErrorMsg()); }
		  while($r1 = $rs1->FetchRow())
		  {
			$category['cid'][] = $r1['cid'];
			$category['category'][$r1['cid']] = $this->SfStr->getSafeString($r1['category'],SAFE_STRING_TEXT);
		  }
		  $data['cid'] = $category['cid'];
		  $this->smarty->assign('category',$category);
		  
		  
		  if(isset($erruid[$r['uid']]))
          {$data['users'][$x]['erruid'] = 1; }
		//}
		$template = 'admin_b.tpl';
		$this->smarty->assign_by_ref('data',$data);
	    $retval = $this->smarty->Fetch($this->template.'/'.$template);
        return $retval;
	}
	
	/**************************************
    * ACTUALIZAR USUARIOS ADMINISTRADORES *
    ***************************************/
    function actualizar_admin_users()
    {

        $retval = FALSE;
        $errmsg = array();
        $erruid = array();
	
		
      foreach($_REQUEST['name'] as $a_id => $name)
        {
          
			if(empty($name) && empty($_REQUEST['email'][$a_id]) && empty($_REQUEST['username'][$a_id]) && empty($_REQUEST['password'][$a_id]))
            {  //si estan vacios esos campos entonces no hace nada y se salta a la siguiente fila en foreach
                continue;
			}	
				$input = array();
                $input['a_id'] = (int)$a_id;
                $input['name'] = $this->SfStr->getSafeString($name,SAFE_STRING_DB);
                $input['email'] = $this->SfStr->getSafeString($_REQUEST['email'][$a_id],SAFE_STRING_DB);
				$input['place'] = $this->SfStr->getSafeString($_REQUEST['place'][$a_id],SAFE_STRING_DB);
				
				
				if($a_id == 0)
				{ $input['type'] = '0';	}
				else
				{ $input['type'] = $this->SfStr->getSafeString($_REQUEST['type_'.$a_id],SAFE_STRING_DB); }
				
	           	$active_admin="0";
				if(isset($_REQUEST['active'][$a_id]))//quiere decir cuando ha habido checked sobre el; esta activo
				{	$active_admin="1";	}
				else
				{	$active_admin="0";	}
				$input['active'] = $this->SfStr->getSafeString($active_admin,SAFE_STRING_DB);

                if(!empty($_REQUEST['username'][$a_id]))
                {
                    $chka_id = $this->check_username(0, $_REQUEST['username'][$a_id]);
                    if($chka_id && $chka_id != $input['a_id'])
                    {
                        $username = $this->SfStr->getSafeString($_REQUEST['username'][$a_id],SAFE_STRING_TEXT);
                        $errmsg[$a_id] = "Username '{$username}' already in use.";
                        $erruid[$a_id] = 1;
                    }
                    else
                    { $input['username'] = $this->SfStr->getSafeString($_REQUEST['username'][$a_id],SAFE_STRING_DB); }
                }
                else
                {
                    $errmsg[1] = 'No se grabo los cambios, porque el campo nombre de usuario, no Puede Estar Vacio.';
                    $erruid[$a_id] = 1;
                }
				
				if (empty($_REQUEST['password'][$a_id]))
				{
					$errmsg[2] = 'No se grabo los cambios porque el campo de la clave no puede estar vacia.';
					$erruid[$a_id] = 1;
				}else if($_REQUEST['actual_password'][$a_id] == $_REQUEST['password'][$a_id])
                { $input['password'] = $this->SfStr->getSafeString($_REQUEST['actual_password'][$a_id],SAFE_STRING_DB); }
				else if ($_REQUEST['actual_password'][$a_id] != $_REQUEST['password'][$a_id])
				{ $input['password'] = $this->SfStr->getSafeString(md5($_REQUEST['password'][$a_id]),SAFE_STRING_DB); } 				
							
                
				if(!isset($erruid[$a_id]))//si no hay cajones en blanco empieza el guardado de datos
                {   
                  $query = "UPDATE {$this->CONF['db_tbl_prefix']}admin SET name = {$input['name']}, email = {$input['email']}, username = {$input['username']},
                            password = {$input['password']},  place = {$input['place']}, type = {$input['type']}, active = {$input['active']} WHERE a_id = {$input['a_id']}";
				  $rs = $this->db->Execute($query);
	              if($rs === FALSE)
	              { $errmsg[$uid] = 'Error updating user data: ' . $this->db->ErrorMsg(); }
					    
				  $query1 = "DELETE FROM {$this->CONF['db_tbl_prefix']}admin_type_category WHERE a_id = {$input['a_id']}";
				  $rs1 = $this->db->Execute($query1);
				  if($rs1 === FALSE)
				  { $error[$uid] = 'Error deleting users: ' . $this->db->ErrorMsg(); }
				  if (isset($_REQUEST['type_'.$input['a_id']]) && $_REQUEST['type_'.$input['a_id']] == '2')
				  {
				     if (isset($_REQUEST['tipos_'.$input['a_id']]))
					 {
					   $tipo = array();
					   $tipo = explode("/",$_REQUEST['tipos_'.$input['a_id']]);
					   for($x=0;$x<count(explode("/",$_REQUEST['tipos_'.$input['a_id']]));$x++)
					   {
					     $query2 = "INSERT INTO {$this->CONF['db_tbl_prefix']}admin_type_category (a_id, cid)
									VALUES (".$a_id.", ".$tipo[$x].")";											
						 $rs2 = $this->db->Execute($query2);
					   }			
					 }
				  }
                }
			}
        if(!empty($errmsg))
        { 
            $this->setMessage('Error',implode('<br />',$errmsg),MSGTYPE_ERROR);
        }else
        {
        	$this->setMessage('&nbsp;','se actualizo correctamente',MSGTYPE_NOTICE);
        }
        /*
        $this->setMessageRedirect('admin.php');
		$this->setMessage('&nbsp;','se actualizo correctamente',MSGTYPE_NOTICE);
        */
      
		header("Location: {$this->CONF['html']}/admin.php");
        exit();

        //return $erruid;
    }
	
    /************************************
    * INSERTAR USUARIOS ADMINISTRADORES *
    *************************************/
    function insert_admin_users()
    {

        $retval = FALSE;
        $errmsg = array();
        $erruid = array();
	
		
      foreach($_REQUEST['name'] as $a_id => $name)
        {
          
			if(empty($name) && empty($_REQUEST['email'][$a_id]) && empty($_REQUEST['username'][$a_id]) && empty($_REQUEST['password'][$a_id]))
            {  
                continue;
			}	
				$input = array();
                $input['a_id'] = (int)$a_id;
                $input['name'] = $this->SfStr->getSafeString($name,SAFE_STRING_DB);
                $input['email'] = $this->SfStr->getSafeString($_REQUEST['email'][$a_id],SAFE_STRING_DB);
				$input['place'] = $this->SfStr->getSafeString($_REQUEST['place'][$a_id],SAFE_STRING_DB);
				$input['type'] = $this->SfStr->getSafeString($_REQUEST['type_'.$a_id],SAFE_STRING_DB);
	
				$active_admin="0";
				if(isset($_REQUEST['active'][$a_id]))//quiere decir cuando ha habido checked sobre el; esta activo
				{	$active_admin="1";	}
				else
				{	$active_admin="0";	}
				$input['active'] = $this->SfStr->getSafeString($active_admin,SAFE_STRING_DB);

                if(!empty($_REQUEST['username'][$a_id]))
                {
                    $chka_id = $this->check_username(0, $_REQUEST['username'][$a_id]);
                    if($chka_id && $chka_id != $input['a_id'])
                    {
                        $username = $this->SfStr->getSafeString($_REQUEST['username'][$a_id],SAFE_STRING_TEXT);
                        $errmsg[$a_id] = "Username '{$username}' already in use.";
                        $erruid[$a_id] = 1;
                    }
                    else
                    { $input['username'] = $this->SfStr->getSafeString($_REQUEST['username'][$a_id],SAFE_STRING_DB); }
                }
                else
                {
                    $errmsg[1] = 'No se agrego usuario, porque campo, nombre de usuario, no puede estar vacio.';
                    $erruid[$a_id] = 1;
                }
				
				if (empty($_REQUEST['password'][$a_id]))
				{
					$errmsg[2] = 'No se agrego usuario, porque campo clave, no puede estar vacio.';
					$erruid[$a_id] = 1;
				}else if($_REQUEST['actual_password'][$a_id] == $_REQUEST['password'][$a_id])
                { $input['password'] = $this->SfStr->getSafeString($_REQUEST['actual_password'][$a_id],SAFE_STRING_DB); }
				else if ($_REQUEST['actual_password'][$a_id] != $_REQUEST['password'][$a_id])
				{ $input['password'] = $this->SfStr->getSafeString(md5($_REQUEST['password'][$a_id]),SAFE_STRING_DB); } 				
							
                if(!isset($erruid[$a_id]))//cuando no hay errores en el llenado de datos osea no hay datos en blanco
                {   
                    if($a_id{0} == 'x')
                    { 
						if (isset($_REQUEST['type_x0']))
						{ 
							$input['type'] = $_REQUEST['type_x0']; 
						}
						else
						{
							$errmsg[3] = 'Type must be choosen.';
							$erruid[$a_id] = 1;
						}
						
						$a_id = $this->db->GenID($this->CONF['db_tbl_prefix'].'admin_sequence');
						
                        $query = "INSERT INTO {$this->CONF['db_tbl_prefix']}admin (a_id, name, email, username, password, place, type, active)
                                  VALUES ($a_id, {$input['name']},{$input['email']},{$input['username']},{$input['password']},{$input['place']},{$input['type']},{$input['active']})";
						$rs = $this->db->Execute($query);
	                    if($rs === FALSE)
	                    { $errmsg[$uid] = 'Error inserting user data: ' . $this->db->ErrorMsg(); }
						
						else
						{
							if (isset($_REQUEST['type_x0']) && $_REQUEST['type_x0'] == '2')
							{				
								if (isset($_REQUEST['tipos_x0']))
								{
									$tipo = array();
									$tipo = explode("/",$_REQUEST['tipos_x0']);
									for($x=0;$x<count(explode("/",$_REQUEST['tipos_x0']));$x++)
									{
										$query2 = 	"INSERT INTO {$this->CONF['db_tbl_prefix']}admin_type_category (a_id, cid)
													VALUES (".$a_id.", ".$tipo[$x].")";											
										$rs2 = $this->db->Execute($query2);
									}			
								}
							}
						}
                    }
                   
				}
			}
        if(!empty($errmsg))
        {
            $this->setMessage('Error',implode('<br />',$errmsg),MSGTYPE_ERROR);
        }else
        {
        	$this->setMessage('&nbsp;','se agrego usuario correctamente',MSGTYPE_NOTICE);
        }
        header("Location: {$this->CONF['html']}/admin.php");
        exit();

        //return $erruid;
    }

   

    //Delete user matching $uid from
    //"users" table and return result
    function delete_user($a_id)
    {
        $a_id = (int)$a_id;
        $query = "DELETE FROM {$this->CONF['db_tbl_prefix']}admin WHERE a_id = $a_id AND sid = 0";
        $rs = $this->db->Execute($query);
        return $rs;
    }

    //Determine if a username is already in
    //user for a given survey.
    //Returns uid of match or false if username
    //is not being used.
    //$username is assumed to be passed unescaped for
    //the database. Use third parameter to
    //turn off database escaping within the function
    function check_username($sid,$username,$escape=1)
    {
        $sid = (int)$sid;

        if($escape)
        { $username = $this->SfStr->getSafeString($username,SAFE_STRING_DB); }
        else
        { $username = $this->SfStr->getSafeString($username,SAFE_STRING_ESC); }

        $query = "SELECT a_id FROM {$this->CONF['db_tbl_prefix']}admin WHERE username = {$username}";
        $rs = $this->db->Execute($query);
        if($rs === FALSE)
        { $this->error('Error checking for existing username: ' . $this->db->ErrorMsg()); }

        if($r = $rs->FetchRow($rs))
        { $retval = $r['a_id']; }
        else
        { $retval = FALSE; }

        return $retval;
    }

}

?>